package com.happy.system.service.impl;

import com.happy.system.domain.*;
import com.happy.system.domain.vo.EmotionDataInfo;
import com.happy.system.domain.vo.EmotionTableDataInfo;
import com.happy.system.domain.vo.NumberInfo;
import com.happy.system.domain.vo.TotalReportInformation;
import com.happy.system.mapper.EmployeeMapper;
import com.happy.system.mapper.SysDeptMapper;
import com.happy.system.repository.ReportRepository;
import com.happy.system.service.IReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    ReportRepository reportRepository;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    SysDeptMapper deptMapper;

    /**
     * 返回用户情绪记录
     * @param employee_id
     * @return
     */
    @Override
    public List<EmoList> getEmoList(Long employee_id)
    {
       return  reportRepository.getEmoList(employee_id);
    }

    /**
     * 返回各部门当日检测人数
     * @return
     */
    @Override
    public List<ReportDept> getReportCountByDepartment()
    {
        List<ReportDept> reportDeptList=reportRepository.getReportCountByDepartment();
        return reportDeptList;
    }

    /**
     * 返回各部门当日检测高压人数
     * @return
     */
    @Override
    public List<StressDept> getStressCountByDepartment(){
        List<StressDept> stressDepts=reportRepository.getStressCountByDepartment();
        return stressDepts;
    }
    /**
     * 获取部门人数信息
     * @param deptId
     * @return
     */
    @Override
    public NumberInfo getNumInfoOfDept(Long deptId) {
        NumberInfo info = new NumberInfo();
        info.setSum(employeeMapper.sumNumOfEmployeeOfDept(deptId));
        info.setMale(employeeMapper.maleNumOfEmployeeOfDept(deptId));
        info.setFemale(employeeMapper.femaleNumOfEmployeeOfDept(deptId));
        return info;
    }
    /**
     * 返回不同压力的人数信息
     * @param deptId
     * @return
     */
    @Override
    public List<NumberInfo> getNumOfStressOfDept(Long deptId){
        List<NumberInfo> numberInfos = new ArrayList<>();
        numberInfos.add(reportRepository.getHighStressNumInfoOfDept(deptId));
        numberInfos.add(reportRepository.getMidStressNumInfoOfDept(deptId));
        numberInfos.add(reportRepository.getlowStressNumInfoOfDept(deptId));
        return numberInfos;
    }

    /**
     * 获取部门压力前三的员工
     * @param deptId
     * @return
     */
    public List<Employee> getHighestStressEmployeeOfDept(Long deptId){
        return reportRepository.getHighestStressEmployeeOfDept(deptId);
    }

    @Override
    public EmotionDataInfo getEmotionDataInfo(Long deptId) {
        List<Report> reports=reportRepository.getReportToday(deptId);
        // Filter to get the latest report for each employee
        Map<Long, Report> latestReportsByEmployee = reports.stream()
                .collect(Collectors.toMap(
                        Report::getEmployee_id,
                        report -> report,
                        (existing, replacement) -> existing.getCreate_time().after(replacement.getCreate_time()) ? existing : replacement
                ));
        System.out.println(latestReportsByEmployee);

        // Aggregate emotion data
        EmotionDataInfo emotionDataInfo = new EmotionDataInfo();
        latestReportsByEmployee.values().forEach(report -> {
            emotionDataInfo.setHappy_sum(emotionDataInfo.getHappy_sum() + ("happy".equals(report.getEmotion()) ? 1 : 0));
            emotionDataInfo.setSad_sum(emotionDataInfo.getSad_sum() + ("sad".equals(report.getEmotion()) ? 1 : 0));
            emotionDataInfo.setSurprised_sum(emotionDataInfo.getSurprised_sum() + ("surprised".equals(report.getEmotion()) ? 1 : 0));
            emotionDataInfo.setAnger_sum(emotionDataInfo.getAnger_sum() + ("anger".equals(report.getEmotion()) ? 1 : 0));
            emotionDataInfo.setNeutral_sum(emotionDataInfo.getNeutral_sum() + ("neutral".equals(report.getEmotion()) ? 1 : 0));
            emotionDataInfo.setFear_sum(emotionDataInfo.getFear_sum() + ("fear".equals(report.getEmotion()) ? 1 : 0));
            emotionDataInfo.setDisgust_sum(emotionDataInfo.getDisgust_sum() + ("disgust".equals(report.getEmotion()) ? 1 : 0));
        });

        return emotionDataInfo;
    }


    /**信息中心**/
    @Override
    public TotalReportInformation getReportInformation() {
        // 获取当天的所有报告
        List<Report> reports = reportRepository.findAll();
        Date date=new Date();
        // 过滤出当天的报告（只比较日期部分）
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);

        List<Report> dailyReports = reports.stream()
                .filter(report -> {
                    Calendar reportCalendar = Calendar.getInstance();
                    reportCalendar.setTime(report.getCreate_time());
                    return reportCalendar.get(Calendar.YEAR) == year &&
                            reportCalendar.get(Calendar.DAY_OF_YEAR) == dayOfYear;
                })
                .collect(Collectors.toList());


        // 按员工ID去重，保留最新的报告
        Map<String, Report> uniqueReports = new HashMap<>();
        for (Report report : dailyReports) {
            String key = report.getEmployee_id().toString();
            if (!uniqueReports.containsKey(key) || uniqueReports.get(key).getCreate_time().before(report.getCreate_time())) {
                uniqueReports.put(key, report);
            }
        }

        // 统计信息初始化
        TotalReportInformation information = new TotalReportInformation();
        int totalReports = 0;
        int maleReports = 0;
        int femaleReports = 0;
        int highStressTotal = 0;
        int mediumStressTotal = 0;
        int lowStressTotal = 0;
        int highStressMale = 0;
        int mediumStressMale = 0;
        int lowStressMale = 0;
        int highStressFemale = 0;
        int mediumStressFemale = 0;
        int lowStressFemale = 0;

        // 统计数据
        for (Report report : uniqueReports.values()) {
            totalReports++;
            Employee employee = employeeMapper.queryEmployeeById(report.getEmployee_id());
            String sex = employee.getSex();
            boolean isMale = "0".equalsIgnoreCase(sex);//男
            boolean isFemale = "1".equalsIgnoreCase(sex);//女

            if (isMale) {
                maleReports++;
            } else if (isFemale) {
                femaleReports++;
            }

            int stress = report.getStress();
            if (stress >= 70) {
                highStressTotal++;
                if (isMale) {
                    highStressMale++;
                } else if (isFemale) {
                    highStressFemale++;
                }
            } else if (stress >= 40) {
                mediumStressTotal++;
                if (isMale) {
                    mediumStressMale++;
                } else if (isFemale) {
                    mediumStressFemale++;
                }
            } else {
                lowStressTotal++;
                if (isMale) {
                    lowStressMale++;
                } else if (isFemale) {
                    lowStressFemale++;
                }
            }
        }

        // 设置统计结果
        information.setTotalReports(totalReports);
        information.setMaleReports(maleReports);
        information.setFemaleReports(femaleReports);
        information.setHighStressTotal(highStressTotal);
        information.setMediumStressTotal(mediumStressTotal);
        information.setLowStressTotal(lowStressTotal);
        information.setHighStressMale(highStressMale);
        information.setMediumStressMale(mediumStressMale);
        information.setLowStressMale(lowStressMale);
        information.setHighStressFemale(highStressFemale);
        information.setMediumStressFemale(mediumStressFemale);
        information.setLowStressFemale(lowStressFemale);

        return information;
    }


    public EmotionTableDataInfo getEmotionTableDataInfo(){
        EmotionTableDataInfo info = new EmotionTableDataInfo();

        Map<Long,List<Integer>> data=reportRepository.getTableDataInfo();

        // 初始化部门名称列表
        info.setDeptName(new ArrayList<>());
        // 初始化情绪数据列表
        info.setEmotionData(new ArrayList<>());

        // 遍历数据map，将数据转换为EmotionTableDataInfo对象
        data.forEach((deptId, emotionCounts) -> {
            // 获取部门名称并添加到deptName列表中
            String deptName = deptMapper.getDeptNameById(deptId); // 假设有获取部门名称的方法
            info.getDeptName().add(deptName);

            // 将每种情绪的数量转换为Long类型并添加到emotionData列表中
            List<Integer> emotionDataList = new ArrayList<>(emotionCounts);
            info.getEmotionData().add(emotionDataList);
        });

        EmotionTableDataInfo newInfo = new EmotionTableDataInfo();
        // 初始化部门名称列表
        newInfo.setDeptName(info.getDeptName());
        // 初始化情绪数据列表
        newInfo.setEmotionData(new ArrayList<>());

        List<List<Integer>>newData=info.getEmotionData();

        newData=transformData(newData);

        newInfo.setEmotionData(newData);

        return newInfo;
    }

    public static List<List<Integer>> transformData(List<List<Integer>> data) {
        // 确定结果的大小
        int numRows = data.size();
        int numCols = data.get(0).size();

        // 初始化结果列表
        List<List<Integer>> transformedData = new ArrayList<>(numCols);
        for (int i = 0; i < numCols; i++) {
            transformedData.add(new ArrayList<>(numRows));
        }

        // 填充结果列表
        for (List<Integer> row : data) {
            for (int i = 0; i < row.size(); i++) {
                transformedData.get(i).add(row.get(i));
            }
        }

        return transformedData;
    }
}
